<template>
  <div class="dashboard">
    <el-container>
      <el-header>
        <h2>大棚监控系统</h2>
      </el-header>

      <el-main>
        <el-row :gutter="20">
          <!-- 大棚信息 -->
          <el-col :span="24">
            <el-card>
              <template #header>
                <div class="card-header">
                  <span>大棚基本信息</span>
                </div>
              </template>
              <div v-if="greenhouse" class="greenhouse-info">
                <p><strong>名称：</strong>{{ greenhouse.name }}</p>
                <p><strong>地址：</strong>{{ greenhouse.address }}</p>
                <p><strong>面积：</strong>{{ greenhouse.area }}平方米</p>
                <p><strong>设备总数：</strong>{{ devices.length }}</p>
              </div>
            </el-card>
          </el-col>

          <!-- 传感器数据 -->
          <el-col :span="12">
            <el-card class="sensor-card">
              <template #header>
                <div class="card-header">
                  <span>实时传感器数据</span>
                </div>
              </template>
              <el-row :gutter="20">
                <el-col :span="8" v-for="device in sensorDevices" :key="device.id">
                  <el-card shadow="hover">
                    <h3>{{ device.name }}</h3>
                    <div v-if="device.latestData">
                      <h4>{{ device.latestData.value }}{{ device.unit }}</h4>
                      <p>更新时间: {{ formatDate(device.latestData.createTime) }}</p>
                    </div>
                  </el-card>
                </el-col>
              </el-row>
            </el-card>
          </el-col>

          <!-- 监控画面 -->
          <el-col :span="12">
            <el-card>
              <template #header>
                <div class="card-header">
                  <span>实时监控</span>
                </div>
              </template>
              <div id="ezuikit-player"></div>
            </el-card>
          </el-col>

          <!-- 图表 -->
          <el-col :span="12">
            <el-card>
              <template #header>
                <div class="card-header">
                  <span>土壤温度趋势</span>
                </div>
              </template>
              <div ref="temperatureChart" style="height: 300px"></div>
            </el-card>
          </el-col>

          <el-col :span="12">
            <el-card>
              <template #header>
                <div class="card-header">
                  <span>土壤氮含量</span>
                </div>
              </template>
              <div ref="nitrogenChart" style="height: 300px"></div>
            </el-card>
          </el-col>

          <!-- 历史照片 -->
          <el-col :span="24">
            <el-card>
              <template #header>
                <div class="card-header">
                  <span>历史照片</span>
                </div>
              </template>
              <el-row :gutter="20">
                <el-col :span="6" v-for="photo in photos" :key="photo.id">
                  <el-card shadow="hover">
                    <img :src="photo.photoUrl" style="width: 100%" />
                    <p>{{ formatDate(photo.createTime) }}</p>
                  </el-card>
                </el-col>
              </el-row>
            </el-card>
          </el-col>
        </el-row>
      </el-main>
    </el-container>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, computed, nextTick } from 'vue'
import {
  getGreenhouses,
  getDevices,
  getSensorData,
  getPhotos,
  getCameraToken,
  getLatestSensorData
} from '../api'
import * as echarts from 'echarts'
import EZUIKit from 'ezuikit-js'
import { ElMessage } from 'element-plus'
import axios from 'axios'
import { useRouter } from 'vue-router'

const greenhouse = ref(null)
const devices = ref([])
const photos = ref([])
const temperatureChart = ref(null)
const nitrogenChart = ref(null)
const router = useRouter()
const latestSensorData = ref({})

const formatDate = (date) => {
  return new Date(date).toLocaleString()
}

const fetchLatestSensorData = async () => {
  try {
    for (const device of sensorDevices.value) {
      const response = await getLatestSensorData(device.id)
      if (response.data?.data) {
        latestSensorData.value[device.id] = response.data.data
      }
    }
  } catch (error) {
    console.error('获取最新传感器数据失败:', error)
    ElMessage.error('获取最新传感器数据失败')
  }
}

const sensorDevices = computed(() => {
  return devices.value
    .filter(device => device.deviceType !== 'CAMERA')
    .map(device => ({
      ...device,
      latestData: latestSensorData.value[device.id]
    }))
})

const initCamera = async () => {
  try {
    const cameraDevice = devices.value.find(d => d.deviceType === 'CAMERA')
    if (cameraDevice) {
      const { data: tokenResponse } = await getCameraToken()
      if (!tokenResponse.data) {
        ElMessage.warning('获取摄像头 token 失败')
        return
      }

      const player = new EZUIKit.EZUIKitPlayer({
        id: 'ezuikit-player',
        url: 'ezopen://open.ys7.com/AB9831171/1.hd.live',
        accessToken: tokenResponse.data,
        template: 'standard',
        autoplay: true
      })
    }
  } catch (error) {
    console.error('Error initializing camera:', error)
    ElMessage.error('初始化摄像头失败：' + (error.response?.data?.message || error.message))
  }
}

const initCharts = () => {
  // 温度曲线图
  const tempChart = echarts.init(temperatureChart.value)
  const tempDevice = devices.value.find(d => d.deviceType === 'TEMPERATURE')
  if (tempDevice) {
    getSensorData(tempDevice.id).then(({ data }) => {
      const sensorData = data.data
      tempChart.setOption({
        xAxis: {
          type: 'category',
          data: sensorData.map(d => formatDate(d.createTime))
        },
        yAxis: {
          type: 'value'
        },
        series: [{
          data: sensorData.map(d => d.value),
          type: 'line'
        }]
      })
    })
  }

  // 氮含量柱状图
  const nitroChart = echarts.init(nitrogenChart.value)
  const nitroDevice = devices.value.find(d => d.deviceType === 'NITROGEN')
  if (nitroDevice) {
    getSensorData(nitroDevice.id).then(({ data }) => {
      const sensorData = data.data
      nitroChart.setOption({
        xAxis: {
          type: 'category',
          data: sensorData.map(d => formatDate(d.createTime))
        },
        yAxis: {
          type: 'value'
        },
        series: [{
          data: sensorData.map(d => d.value),
          type: 'bar'
        }]
      })
    })
  }
}

const testConnection = async () => {
  try {
    const token = localStorage.getItem('token')
    console.log('Current token:', token)

    const response = await axios.get('http://localhost:8080/api/greenhouse', {
      headers: {
        'Authorization': `Bearer ${token}`
      }
    })

    console.log('测试连接响应:', response.data)
    ElMessage.success('连接成功')
  } catch (error) {
    console.error('测试连接失败:', error)
    if (error.response) {
      console.log('Error response:', error.response)
      ElMessage.error(`连接失败: ${error.response.data?.message || error.response.statusText}`)
    } else {
      ElMessage.error('连接失败: ' + error.message)
    }
  }
}

onMounted(async () => {
  const token = localStorage.getItem('token')
  console.log('Dashboard mounted, current token:', token)

  if (!token) {
    ElMessage.error('未登录或 token 已失效')
    router.push('/login')
    return
  }

  try {
    console.log('开始获取大棚信息...')
    const greenhouseResponse = await getGreenhouses()
    console.log('大棚信息响应:', greenhouseResponse)

    if (!greenhouseResponse.data?.data) {
      ElMessage.warning('没有找到大棚信息')
      console.log('大棚数据为空')
      return
    }

    greenhouse.value = greenhouseResponse.data.data[0]
    console.log('获取到的大棚信息:', greenhouse.value)

    if (greenhouse.value) {
      console.log('开始获取设备信息...')
      const deviceResponse = await getDevices(greenhouse.value.id)
      console.log('设备信息响应:', deviceResponse)

      if (!deviceResponse.data?.data) {
        ElMessage.warning('没有找到设备信息')
        console.log('设备数据为空')
        return
      }

      devices.value = deviceResponse.data.data
      console.log('获取到的设备信息:', devices.value)

      // 获取最新的传感器数据
      await fetchLatestSensorData()

      // 初始化图表
      await nextTick()
      console.log('开始初始化图表...')
      initCharts()

      // 初始化摄像头
      console.log('开始初始化摄像头...')
      await initCamera()

      // 获取历史照片并按时间排序
      const cameraDevice = devices.value.find(d => d.deviceType === 'CAMERA')
      if (cameraDevice) {
        console.log('开始获取历史照片...')
        const photoResponse = await getPhotos(cameraDevice.id)
        console.log('历史照片响应:', photoResponse)
        if (photoResponse.data?.data) {
          photos.value = photoResponse.data.data.sort((a, b) =>
            new Date(b.createTime) - new Date(a.createTime)
          )
          console.log('获取到的历史照片:', photos.value)
        }
      }
    }
  } catch (error) {
    console.error('加载数据时出错:', error)
    if (error.response) {
      console.error('错误响应:', error.response)
      ElMessage.error(`加载数据失败: ${error.response.data?.message || error.response.statusText}`)
    } else if (error.request) {
      console.error('请求未收到响应')
      ElMessage.error('服务器未响应，请检查网络连接')
    } else {
      console.error('请求配置错误:', error.message)
      ElMessage.error(`请求错误: ${error.message}`)
    }
  }
})

let updateTimer
onMounted(() => {
  updateTimer = setInterval(fetchLatestSensorData, 30000)
})

onUnmounted(() => {
  if (updateTimer) {
    clearInterval(updateTimer)
  }
})
</script>

<style scoped>
.dashboard {
  height: 100vh;
}

.el-header {
  background-color: #409EFF;
  color: white;
  line-height: 60px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.sensor-card {
  margin-bottom: 20px;
}

#ezuikit-player {
  width: 100%;
  height: 400px;
}
</style>